package com.lv.filter;

import com.lv.common.untils.RedisCache;
import com.lv.exception.CaptchaException;
import com.lv.handler.MyFailureHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created with IntelliJ IDEA.
 * <p>
 * 验证码过滤器
 * </p>
 *
 * @Author: 凉薄
 * @Date: 2022/01/07/20:05
 * @Description:
 */
@Component
public class CaptchaFilter extends OncePerRequestFilter {
    @Autowired
    RedisCache redisCache;
    @Autowired
    MyFailureHandler myFailureHandler;
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String url=request.getRequestURI();
        if("/login".equals(url)&&request.getMethod().equals("POST")){
            //校验验证码
         try{
             validate(request);
         }catch (CaptchaException e){
             myFailureHandler.onAuthenticationFailure(request,response,e);
         }

        }
        filterChain.doFilter(request,response);
    }

    private void validate(HttpServletRequest request) throws CaptchaException{
        String uuid=request.getParameter("uuid");
        String captcha=request.getParameter("captcha");
        String redisCaptcha = (String)redisCache.getCacheObject(uuid);
        if(redisCaptcha==null){
            throw new CaptchaException("验证码失效！");
        }else if(!redisCaptcha.equals(captcha)){
            redisCache.deleteObject(uuid);
            throw new CaptchaException("验证码错误！");
        }
        redisCache.deleteObject(uuid);
    }
}
